//
//  AvatarSettingVC.swift
//  WeFamily
//
//  Created by 崔世强 on 2020/7/7.
//  Copyright © 2020 Meak Tsui. All rights reserved.
//

import UIKit
import Kingfisher

class AvatarSettingVC: UIViewController {

    @IBOutlet weak var optionBtn: UIBarButtonItem!
    
    @IBOutlet weak var avatarImageView: UIImageView!
    
    lazy var userService = UserService()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let Defaults = UserDefaults(suiteName: USER_DEFAULTS_NAME)!
        let avatar = Defaults[.userAvatar] ?? ""
        
        avatarImageView.kf.setImage(with: KF.ImageResource(downloadURL: Common.imgOrigUrl(avatar) ?? URL(string: "localhost")!), placeholder: #imageLiteral(resourceName:"defaultAvatar"),options: [.processor(CryptorProcessor())])
    }

    @IBAction func onOptionClicked(_ sender: UIBarButtonItem) {
        let choosePhotoAction = UIAlertAction(title: "从手机相册中选择", style: .default) { (action) in
            TGPhotoPickerManager.shared.takePhoto(presentStyle: .fullScreen,{ config in
                config.tg_padding(8)
                config.maxImageCount = 1
                config.tg_isShowEditButton(true)
                config.tg_checkboxType(.circle)
                config.tg_isShowIndicator(true)
                config.tg_isShowPreviewButton(true)
                config.tg_checkboxBarWH(20)
            }) { (assets, thumbnails, originImgs, datas) in
                let Defaults = UserDefaults(suiteName: USER_DEFAULTS_NAME)!
                let uid = Defaults[.userId] ?? 0
                let imgs = originImgs.filter { $0 != nil}.map { $0! }
                self.view.makeModalToastActivity(.center)
                DispatchQueue.global().async(execute: {
                    imgs.forEach({ (photo) in
                        let fileName = NSUUID().uuidString.replacingOccurrences(of:"-",with: "") + ".jpg"
                        let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] as URL
                        let fileUrl = cacheDir.appendingPathComponent(fileName, isDirectory: false)
                        guard let origImg = photo.jpegData(compressionQuality: 1) else {
                            DispatchQueue.main.async {
                                self.view.hideModalToastActivity()
                                self.view.makeToast("修改失败", duration: 3.0, position: .center)
                            }
                            return
                        }
                        try? origImg.write(to: fileUrl)
//                        OSSTool.instance.putImgFile(fileName, imgFile:fileUrl )
                        IM.request(.upload(dir: "imgs/", file: fileUrl.path, filename: fileName), success: {[unowned self] json in
                            if reqSuccess(json["code"].stringValue) {
                                self.userService.updateMyInfo(uid, avatar: fileName) { success, msg in
                                    DispatchQueue.main.async {
                                        self.view.hideModalToastActivity()
                                        if (success) {
                                            Defaults[.userAvatar] = fileName
                                            AppStatusManager.instance.avatarPath = fileName
                                            self.navigationController?.popViewController(animated: true)
                                        } else {
                                            self.view.makeToast("修改失败", duration: 3.0, position: .center)
                                        }
                                    }
                                }
                            } else {
                                DispatchQueue.main.async {
                                    self.view.hideModalToastActivity()
                                    self.view.makeToast("修改失败", duration: 3.0, position: .center)
                                }
                            }
                        }, error: { code in
                            print(code)
                            DispatchQueue.main.async {
                                self.view.hideModalToastActivity()
                                self.view.makeToast("修改失败", duration: 3.0, position: .center)
                            }
                        }, failure: { error in
                            DispatchQueue.main.async {
                                self.view.hideModalToastActivity()
                                self.view.makeToast("修改失败", duration: 3.0, position: .center)
                            }
                        })
                    })
                })
            }
        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel)
        self.showActionSheet(title: nil, message: "选择", actions: [choosePhotoAction,cancelAction], animated: true)
    }
}
